package com.ruoyi.database.service.impl;



import com.ruoyi.database.config.DataSourceContextHolder;
import com.ruoyi.database.config.DataSourceRouting;
import com.ruoyi.database.mapper.DataSourceMapper;
import com.ruoyi.database.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;


@Service
public class DataSourceServiceImpl implements DataSourceService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private DataSourceRouting dataSourceRouting;


    @Autowired
    private DataSourceMapper killMapper;

    @Autowired
    private DataSource dataSource;


    public static String generateOrderNumber() {
        // 生成一个 UUID
        UUID uuid = UUID.randomUUID();
        // 获取 UUID 的字符串表示，并去掉其中的横杠
        String uuidStr = uuid.toString().replace("-", "");
        // 提取前 8 个字符作为订单号
        return uuidStr.substring(0, 8).toUpperCase();
    }

    public void performDatabaseOperations() {
        try {
            // 切换到主数据源
            DataSourceContextHolder.setDataSourceType("primary");
            // 执行操作
//            killMapper.someMethod(9);

            System.out.println( DataSourceContextHolder.getDataSourceType());

            // 切换到从数据源
            DataSourceContextHolder.setDataSourceType("secondary");
            // 执行操作
//            killMapper.someMethod(9);
            System.out.println( DataSourceContextHolder.getDataSourceType());

            // 如果需要，执行其他方法
            // System.out.println(killMapper.someOtherMethod(1));
        } finally {
            // 清理数据源类型，避免影响到其他操作
            DataSourceContextHolder.clearDataSourceType();
        }

    }


    public void addDataSource(String key) {
        DataSource newDataSource = DataSourceBuilder.create()
                .url("jdbc:mysql://localhost:3306/example_db_slave_"+key+"?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true")
                .username("root")
                .password("123456")
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .build();


        String dynamicLibraryName = "example_db_slave_"+key;

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true","root","123456");
             Statement stmt = conn.createStatement()) {

            // SQL to create the database
            String sql = "CREATE DATABASE IF NOT EXISTS " + dynamicLibraryName ;
            stmt.executeUpdate(sql);
            System.out.println("Database " + key + " created or already exists.");
        } catch (Exception e) {
            e.printStackTrace();
        }


//        添加到动态数据源
        dataSourceRouting.addDataSource(key, newDataSource);

        // 切换到主数据源
        DataSourceContextHolder.setDataSourceType(key);

        //目前数据源
        System.out.println( DataSourceContextHolder.getDataSourceType());

        // 执行写入文件操作
        executeSqlFile(newDataSource,dynamicLibraryName);

        // 执行查询操作
//        System.out.println(killMapper.someOtherMethod222(1));

        DataSourceContextHolder.clearDataSourceType();

    }


    public void executeSqlFile( DataSource newDataSource,String dynamicLibraryName) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(newDataSource);

        // 创建 SQL 语句
        String dropDatabaseSql = "DROP DATABASE IF EXISTS " + dynamicLibraryName + ";";
        String createDatabaseSql = "CREATE DATABASE " + dynamicLibraryName + " DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
        String useDatabaseSql = "USE " + dynamicLibraryName + ";";
        String createTableSql = "CREATE TABLE IF NOT EXISTS example_table (" +
                "    id INT AUTO_INCREMENT PRIMARY KEY, " +
                "    data VARCHAR(255) NOT NULL" +
                ");";
        String enableForeignKeyChecksSql = "SET FOREIGN_KEY_CHECKS = 1;";

        // 执行 SQL 语句
        try (Connection connection = newDataSource.getConnection();
             Statement stmt = connection.createStatement()) {

            System.out.println("开始执行sql语句");
            // 执行每条 SQL 语句
            stmt.execute(dropDatabaseSql);
            stmt.execute(createDatabaseSql);
            stmt.execute(useDatabaseSql);
            stmt.execute(createTableSql);
            stmt.execute(enableForeignKeyChecksSql);
        } catch (SQLException e) {
            throw new RuntimeException("Error executing SQL file", e);
        }


    }


}
